package com.farm.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farm.entity.Cart;
import com.farm.entity.Order;
import com.farm.entity.OrderItem;
import com.farm.entity.Product;
import com.farm.mapper.OrderItemMapper;
import com.farm.mapper.OrderMapper;
import com.farm.service.CartService;
import com.farm.service.OrderService;
import com.farm.service.ProductService;
import com.farm.service.UserService;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private ProductService productService;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public Order createOrder(Long employeeId) {
        // 获取购物车商品
        List<Cart> cartItems = cartService.getUserCart(employeeId);
        if (cartItems.isEmpty()) {
            throw new RuntimeException("购物车为空");
        }

        // 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Cart item : cartItems) {
            Product product = productService.getProductById(item.getProductId());
            totalAmount = totalAmount.add(product.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }

        // 检查余额
        if (!userService.deductBalance(employeeId, totalAmount)) {
            throw new RuntimeException("余额不足");
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setEmployeeId(employeeId);
        order.setTotalAmount(totalAmount);
        order.setStatus(0);
        orderMapper.insert(order);

        // 创建订单详情
        for (Cart item : cartItems) {
            Product product = productService.getProductById(item.getProductId());
            
            // 扣减库存
            if (!productService.updateStock(product.getId(), item.getQuantity())) {
                throw new RuntimeException("商品" + product.getName() + "库存不足");
            }

            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(product.getId());
            orderItem.setFarmerId(product.getFarmerId());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setPrice(product.getPrice());
            orderItem.setSubtotal(product.getPrice().multiply(new BigDecimal(item.getQuantity())));
            orderItemMapper.insert(orderItem);
        }

        // 清空购物车
        cartService.clearUserCart(employeeId);

        return order;
    }

    @Override
    public Order getOrderById(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public IPage<Order> getUserOrders(Long userId, Integer page, Integer size) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("employee_id", userId)
              .orderByDesc("create_time");
        return orderMapper.selectPage(new Page<>(page, size), wrapper);
    }

    @Override
    public IPage<Order> getFarmerOrders(Long farmerId, Integer page, Integer size) {
        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("farmer_id", farmerId)
                  .select("DISTINCT order_id");
        List<OrderItem> items = orderItemMapper.selectList(itemWrapper);

        if (items.isEmpty()) {
            return new Page<>(page, size);
        }

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.in("id", items.stream().map(OrderItem::getOrderId).toArray())
              .orderByDesc("create_time");
        return orderMapper.selectPage(new Page<>(page, size), wrapper);
    }

    @Override
    @Transactional
    public void updateOrderStatus(Long orderId, Integer status) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(status);
        orderMapper.updateById(order);
    }

    @Override
    @Transactional
    public void cancelOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || order.getStatus() != 0) {
            throw new RuntimeException("订单不存在或无法取消");
        }

        // 恢复库存
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        List<OrderItem> items = orderItemMapper.selectList(wrapper);
        
        for (OrderItem item : items) {
            Product product = productService.getProductById(item.getProductId());
            if (product != null) {
                productService.updateStock(product.getId(), -item.getQuantity());
            }
        }

        // 退还余额
        userService.recharge(order.getEmployeeId(), order.getTotalAmount());

        // 更新订单状态
        order.setStatus(3);
        orderMapper.updateById(order);
    }

    @Override
    @Transactional
    public void confirmReceipt(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || order.getStatus() != 1) {
            throw new RuntimeException("订单不存在或状态错误");
        }

        order.setStatus(2);
        orderMapper.updateById(order);
    }

    @Override
    public IPage<Order> getAllOrders(Integer page, Integer size) {
        return orderMapper.selectPage(new Page<>(page, size), 
            new QueryWrapper<Order>().orderByDesc("create_time"));
    }

    private String generateOrderNo() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) 
             + String.format("%04d", (int)(Math.random() * 10000));
    }
} 